<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 客户接口
 */
class Customer extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Customer();

    }

    /**
     * 查看
     */
    public function index()
    {
        $scope = $this->request->request('scope');
        $user = $this->auth->getUserinfo();

        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();

        //共享范围:0=自己独占,1=团队共享, 2=公司全部
        $this->relationSearch = true;
        $total = $this->model
            ->field($field)
            ->where(function ($query) use ($scope,$user) {
                $query->where('company_id',$user['company_id']); //公共条件

                switch ($scope){
                    case 0:
                        $query->where(['scope' => 0,'user_id' => $user['id']]);
                        break;
                    case 1:
                        $query->where(['scope' => 1]);
                        break;
                    default:
                }
            })
            ->where($where)

            ->count();
        $list = $this->model

            ->field($field)
            ->where(function ($query) use ($scope,$user) {
                $query->where('company_id',$user['company_id']); //公共条件

                switch ($scope){
                    case 0:
                        $query->where(['scope' => 0,'user_id' => $user['id']]);
                        break;
                    case 1:
                        $query->where(['scope' => 1]);
                        break;
                    default:
                }
            })
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        $visit = [];
        foreach($list as $k => $v){
            $visit = \app\common\model\Visitlog::getOneVisitLogBycustomerId($v['id']);
            if($visit){
                $list[$k]['visit'] = [
                    'createtime' => $visit['createtime'],
                    'record' => $visit['record']
                ];
            }

        }

        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);
    }

    /**
     * 添加
     */
    public function add()
    {
        $to_id = $this->request->get('to_id',0); //对方用户id
        $this->dataLimit = true;
        if ($this->request->isPost())
        {
            $params = $this->request->post();
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    if($to_id){
                        $to_user = \app\common\model\User::get($to_id);
                        $params['name'] = $to_user['nickname'];
                        $params['mobile'] = $to_user['mobile'];
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 详情
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $row->visitlog;
        $this->success('',$row);

    }



    public function otherdata(){
        //分组:0=类型,1=级别,2=状态
        $data = [
            'type' => \app\admin\model\Tags::getTagsByType(0),
            'level' => \app\admin\model\Tags::getTagsByType(1),
            'status' => \app\admin\model\Tags::getTagsByType(2)
        ];
        $this->success('',$data);
    }

    /**
     * 成交金额
     */
    public function changeTurnover(){
        $turnover = $this->request->request('turnover/d',0);
        $customer_id = $this->request->request('id');

        if($turnover - 1 < 0) $this->error('金额不正确');
        $result = false;
        Db::startTrans();
        try{
            Db::name('customer')->where('id',$customer_id)->update(['turnover' => $turnover]);
            Db::name('user')->where('id',$this->auth->id)->setInc('finish_target',$turnover);
            Db::commit();
            $result = true;

        }catch(\Exception $e){
            Db::rollback();
        }
        if($result){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }

    }

    /**
     * 共有客户抢为独占
     */
    public function changeOwn(){
        $id = $this->request->request('id/d');
        $row = $this->model->get($id);

        if($row['scope'] != 1) $this->error('客户状态不允许抢为独占');
        $row->scope = 0;
        $row->user_id = $this->auth->id;
        $res = $row->save();
        $res !== false ? $this->success('设置成功') : $this->error('设置失败');
    }

    /**
     * 接单记录
     */
    public function record(){
        $type = $this->request->request('type',0); //type: 0=我发的，1=正在进行，2=已完成
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();
        //type: 0=我发的，1=正在进行，2=已完成
        $this->relationSearch = true;
        $total = $this->model
            ->field($field)
            ->where(function ($query) use ($type) {

                if($type == 1){
                    $query->where('user_id',$this->auth->id);
                    $query->where('status','in',[7,8,9]);
                }elseif($type == 2){
                    $query->where('user_id',$this->auth->id);
                    $query->where('status','=',10);
                }else{
                    //我发的
                    $redis = new \Predis\Client(\think\Config::get('redis'));
                    $key = 'customer_creator:' .$this->auth->id;
                    $idArr = $redis->lrange($key,0,100);
                    $query->where('id','in',$idArr);
                }
            })
            ->where($where)
            ->count();
        $list = $this->model
            ->field($field)
            ->where(function ($query) use ($type) {

                if($type == 1){
                    $query->where('user_id',$this->auth->id);
                    $query->where('status','in',[7,8,9]);
                }elseif($type == 2){
                    $query->where('user_id',$this->auth->id);
                    $query->where('status','=',10);
                }else{
                    //我发的
                    $redis = new \Predis\Client(\think\Config::get('redis'));
                    $key = 'customer_creator:' .$this->auth->id;
                    $idArr = $redis->lrange($key,0,100);
                    $query->where('id','in',$idArr);
                }
            })
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        $visit = [];
        foreach($list as $k => $v){
            $visit = \app\common\model\Visitlog::getOneVisitLogBycustomerId($v['id']);
            if($visit){
                $list[$k]['visit'] = [
                    'createtime' => $visit['createtime'],
                    'record' => $visit['record']
                ];
            }

        }


        $result = array("total" => $total, "rows" => $list);
        $this->success('', $result);
    }


}